/**
 * Computer Graphics Lecture WS 2009/2010 Ulm University
 * Creator: Manuel Finckh
 * Email:   manuel.finckh@uni-ulm.de
 */

#ifndef BVH_H
#define BVH_H

#include "rtStructs.h"

struct Node { // modify or extend if needed
  AABB bbox;
  int left; // index to the left child
  int right; // index to the right child

  int triIndex; // indexes the first triangle in the index array
  int numTris; // != 0 -> node is a leaf node
}; // 40 bytes, but can be packt into 32 bytes
// i.e. right = left+1 (right child must directly succeed left child in the node array) => 36 bytes
// indicate inner node or leaf not with just one bit (i.e. sign bit of triIndex)
// the other bits are used for normal indexing (in leafs use as triIndex and in inner nodes use as leftIndex) => 32 bytes

struct TraversalStack {
  int nodeIndex;
  float tmin;
};

struct BVH {
  AABB bbox;
  const Triangle * const tris;
  const int nTris;

  // this is the bvh!
  Node *nodes;
  int addedNodes;
  int *indices; // to index the triangles in the leafes (sorted during bvh construction)

  BVH(const Triangle * const tris, const int nTris);
  ~BVH();

  void buildBVH(int nodeIndex, int triIndex, int numTris, AABB box, int depth); // recursive construct BVH
  inline int sortTris(int triIndex, int numTris, float plane, int axis, AABB &leftBox, AABB &rightBox);

  HitRec intersect(const Ray &ray) const;

  // add extra methods if needed (i.e. sortTriangles(...))
};

#endif

